<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\WineDrinkKeywords;
use Illuminate\Support\Facades\DB;

class WineProductDrinkRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\WineProductDrink";

    protected $appendCreatorAndUpdater = true;
    protected $appendUserId = true;

    protected function commonRules()
    {
        return [
            'product_id' => 'required',
            'keywords'=>'required|array|max:4',
            'consume' => 'required',
            'wineglass' => 'required',
            'sober_time' => 'required',
            'temperature' => 'required',
            //'delicacy' => 'required',
            'chinese_food' => 'required',
            'western_food' => 'required',
            'snack' => 'required',
            'undelicacy' => 'required',
            'talk_keywords' => 'required'
        ];
    }

    protected function commonMessages()
    {
        return [
            'keywords.max'=>'味道关键词最多:max个'
        ];
    }

    protected function commonSave($model)
    {
        if($this->request->has('keywords')){
            $rows = $this->request->input('keywords',[]);
            DB::table('wine_drink_keywords')->where('drink_id','=',$model->id)->delete();
            foreach ($rows as $row){
                if (isset($row['keyword_id'])&&isset($row['text'])){
                    if($word = DB::table('wine_taste_keywords')->whereNull('deleted_at')->where('id','=',$row['keyword_id'])->first()){
                        $m = new WineDrinkKeywords();
                        $m->product_id = $model->product_id;
                        $m->drink_id = $model->id;
                        $m->keyword_id = $word->id;
                        $m->keyword = $word->name;
                        $m->keyword_pic = $word->icon;
                        $m->text = $row['text'];
                        $m->save();
                    }
                }
            }
        }

    }

    protected function processStoreValidate()
    {
        $c = $this->query()->where('product_id','=',$this->request->input('product_id'))->count();
        if($c > 0) {
            $this->error = 'Drink介绍记录已存在，请勿重复添加！';
            return false;
        }
        return true;
    }
}